package com.softserveinc.cheatsheet.services;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.softserveinc.cheatsheet.dao.UserAccountDao;
import com.softserveinc.cheatsheet.entity.UserAccount;
import com.softserveinc.cheatsheet.entity.UserAuthority;


public class UserService implements UserDetailsService {
	

	private UserAccountDao userAccountDao;

	@Override
	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		UserAccount result = userAccountDao.read(userName);
		if (result == null)
			throw new UsernameNotFoundException("No user, with name "
					+ userName);
		return result;		
	}
	
	public UserAccount saveUser(UserAccount user){
		
		try {
			UserAuthority userAuthority = userAccountDao.readUserRole(UserAuthority.ROLE_USER);
			user.addAuthority(userAuthority);
		} catch (EmptyResultDataAccessException e) {
			System.out.println("ROLE_USER is not defined among User Authorities");
		}
		
		userAccountDao.create(user);
		UserAccount createdUser = userAccountDao.read(user.getUsername());
		System.out.println(createdUser);
		return createdUser;
	}
	
	public void createAuthority(String authorityName) {
		userAccountDao.create(new UserAuthority(authorityName));
	}
	
	public List<UserAccount> getAllUsers(){
		return userAccountDao.list();
	}

	@Autowired
	public void setUserAccountDao(UserAccountDao userAccountDao) {
		this.userAccountDao = userAccountDao;
	}
}
